import {Injectable} from '@angular/core';
import {MessageService} from './message.service';
import {AlertMessage} from '../entity/alert-message';
import {RequestParam} from '../entity/request-param';
import {Observable} from 'rxjs/index';
import {TpHttpService} from './tp-http.service';
import {BaseResponse} from '../entity/base-response';
import {InvokeDataRest} from '../entity/invoke-data-rest';
import {InvokeDataDubbo} from '../entity/invoke-data-dubbo';
import {InvokeResultDto} from '../entity/invoke-result-dto';

@Injectable({
    providedIn: 'root'
})
export class SendService {
    constructor(private messageService: MessageService,
                private httpService: TpHttpService) {
    }

    send(data: InvokeDataRest): Observable<any> {
        if (!this.checkInvokeData(data)) {
            // 参数检查不通过
            return;
        }

        return this.httpService.post('/api/invoke', JSON.stringify(data));
    }

    checkInvokeData(data: InvokeDataRest): boolean {
        const errors = [];
        this.checkInvokeParams('路径参数', data.pathParams, errors);
        this.checkInvokeParams('URL参数', data.params, errors);
        this.checkInvokeParams('请求头参数', data.headers, errors);

        if (errors && errors.length > 0) {
            errors.forEach(errorInfo => {
                this.messageService.add(<AlertMessage> {
                    id: errorInfo.id,
                    type: 'error',
                    html: errorInfo.msg,
                    time: 10
                });
            });
            return false;
        }

        return true;
    }

    save(data: InvokeDataRest): Observable<BaseResponse<InvokeDataRest>> {
        return this.httpService.post<BaseResponse<InvokeDataRest>>('/api/invoke/save', JSON.stringify(data));
    }

    saveDubbo(data: InvokeDataDubbo): Observable<BaseResponse<InvokeDataDubbo>> {
        return this.httpService.post<BaseResponse<InvokeDataDubbo>>('/api/invoke/save/dubbo', JSON.stringify(data));
    }

    private checkInvokeParams(moduleName: string, params: RequestParam[], errors: any[]) {
        if (params) {
            params.forEach(param => {
                if (!param.match) {
                    errors.push({
                        id: moduleName + ':' + param.key,
                        msg: moduleName + '：' + param.key + '=' + param.value + '，不合法！'
                    });
                }
            });
        }
    }

    invokeDubbo(data: InvokeDataDubbo): Observable<BaseResponse<InvokeResultDto>> {
        return this.httpService.post('/api/invoke/dubbo', JSON.stringify(data));
    }
}
